<?php
namespace app\api\controller\v1;
use app\common\controller\Api;
use think\Controller;
use think\Request;
use think\Validate;
use think\Db;
use think\Env;
require_once APP_PATH . '/api/common.php';

class Share extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function upload(Request $request)
    {
        $user =$this->auth->getUser(true) ;
        $userId = $user['uid'] ?? 0;
        $validate = new Validate();
        $validate->rule([
            'user_id' => 'require|number',
        ]);
        if (!$validate->check(['user_id' => $userId])) {
            return json(['code' => 0, 'msg' => $validate->getError(), 'data' => []]);
        }

        $file = $request->file('file');
        if (!$file) {
            return json(['code' => 0, 'msg' => '未选择文件', 'data' => []]);
        }

        $dateDir = date('Ymd');
        $saveDir = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR .  'uploads' . DIRECTORY_SEPARATOR . 'share' . DIRECTORY_SEPARATOR . $dateDir;
        if (!is_dir($saveDir)) {
            @mkdir($saveDir, 0777, true);
        }

        $ext = strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION));
        $allow = ['jpg','jpeg','png','gif','bmp','webp'];
        if (!in_array($ext, $allow)) {
            return json(['code' => 0, 'msg' => '仅支持图片格式文件', 'data' => []]);
        }

        $newName = date('His') . '_' . $userId . '_' . mt_rand(1000,9999) . '.' . $ext;
        $target = $saveDir . DIRECTORY_SEPARATOR . $newName;

        try {
            move_uploaded_file($file->getPathname(), $target);
            $now = date('Y-m-d H:i:s');
            $url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $target);
            $url = str_replace('\\', '/', $url);
            $target=getImg($target,512,512);
            $target=preg_replace("/https\:\/\/dev002\.gxyushengwenhua\.com/",$_SERVER['DOCUMENT_ROOT'],$target);
            list($imagewidth, $imageheight) = @getimagesize($target);

            $fa_attachment = Db::name('fa_attachment')->insertGetId([
                'user_id'    => intval($userId),
                'type'       => 'share',
                'imagetype'  => $ext,
                'filename'  => $newName,
                'filesize'  => @filesize($target)??0,
                'imagewidth'  => $imagewidth??512,
                'imageheight'  => $imageheight??512,
                'url'  => $url,
                'uploadtime'=> strtotime($now),
                'updatetime'=> strtotime($now),
            ]);
            //echo 22;exit;
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '保存失败', 'data' => []]);
        }

        $today = date('Y-m-d');
        $now = date('Y-m-d H:i:s');
        $start = strtotime($today . ' 00:00:00');
        $end   = strtotime($today . ' 23:59:59');
        $sum = Db::name('user_points')
            ->where('user_id', intval($userId))
            ->where('remarks', '分享上传')
            ->where('create_time', '>=', $start)
            ->where('create_time', '<=', $end)
            ->sum('points');

        $sum = intval($sum);
        if ($sum >= 100) {
            return json(['code' => 200, 'msg' => '今日积分已达上限', 'data' => ['url' => $url, 'added_points' => 0, 'today_points' => $sum]]);
        }

        $add = 2;
        if ($sum + $add > 100) {
            $add = 100 - $sum;
        }

        if ($add > 0) {
            $userPointsModel = new \app\admin\model\UserPoints();
            list($sum, $add, $totalPoints, $todayCount) = $userPointsModel->addPoints($userId, $add, 'share', $fa_attachment, '分享上传',0,2,'分享上传');
        }

        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/../runtime/logs/share_upload.log', date('Y-m-d H:i:s') . ' ' . json_encode(['user_id' => $userId, 'file' => $target, 'points' => $add], JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
        $urlauto= Env::get('img.baseurl') . $url;
        $data=@file_get_contents($urlauto);
        if($data===false){
            $urlauto= Env::get('base.baseapiurl') . $url;
        }
        echo json_encode(array('code' => 200, 'msg' => '上传成功', 'data' => ['url' => $urlauto, 'added_points' => $add, 'today_points' => $sum, 'total_points' => $totalPoints, 'today_count' => $todayCount]));
        exit;
        //$this->success('上传成功', ['url'=>$urlauto,'added_points'=>$add,'today_points'=>$sum,'total_points'=>$totalPoints,'today_count'=>$todayCount]);
    }

    private function pubUrl($abs)
    {
        $doc = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);
        $root = realpath($doc . DIRECTORY_SEPARATOR . '..');
        $rel = str_replace($root, '', $abs);
        $rel = str_replace(DIRECTORY_SEPARATOR, '/', $rel);
        return $rel;
    }
}
